srvMap.add('querySubRegionInfo', '','front/sh/sceneMonitor!execute?uid=querySubRegionInfo');//查询子区域数据
srvMap.add('querySubRegionWarn', '','front/sh/sceneMonitor!execute?uid=querySubRegionWarn');//查询区域预警信息
srvMap.add('warnDealById', '','front/sh/sceneMonitor!execute?uid=warnDealById');//预警处理
srvMap.add('queryCamera', '','front/sh/sceneMonitor!execute?uid=queryCamera');//根据经纬度范围查询摄像头
srvMap.add('trendForecast', '','front/sh/sceneMonitor!execute?uid=trendForecast');//客流预测
srvMap.add('queryWarnDealInfoById', '','front/sh/sceneMonitor!execute?uid=queryWarnDealInfoById');//预警处理，信息查询（非群发）
srvMap.add('queryComfortLevel', '','front/sh/sceneMonitor!execute?uid=queryComfortLevel');//查询景区舒适度信息

var map; // 百度地图实例
var centerLng = ""; // 地图中心点经度
var centerLat = ""; // 地图中心点维度
var zoomLevel = ""; // 地图级别
var regionInfo; // 区域预警信息，做缓存
var warnMarkerArr = []; // 当前告警标注
var allWarnMarkerArr = []; //存放所有小人图标
var _intvl_all = null;
var labelColorGreen = "#28C613"; //"#28C613";
var labelColorYellow = "#FBEA02"; //"#FBEA02";
var labelColorOrange = "#FF8148"; //"#FF8148";
var labelColorRed = "#FF0000"; //"#FF0000";
var warnId; // 区域预警Id

var warnMessageInfoObj = {};	//缓存管理员手机号码

var cameraMarkerList = [];//摄像机覆盖物缓存列表
var cameraFlag = "close";
var trendFlag = "close";
$(function() {
	// 初始化页面
	$(document).ready(function(){
		initPage();

		$(window).resize(function() {
			// 初始化页面
			initPage();
		});
		//初始化页面权限
		initFuncAuth();
		// 初始化页面数据
		initPageData();

		$(".btnBack").click(function() {
			location.href = CONTENT_PATH + "/zhly/scene_monitor.jsp";
		});

		$("#dealRecordBtn").click(function(){
			if("none" == $("#dealRecord").css("display")){
				$(this).addClass("record_arrow_on");
				$("#dealRecord").show();
			}else{
				$(this).removeClass("record_arrow_on");
				$("#dealRecord").hide();
			}
		});
		$("#dealRecord").mouseleave(function(){
			$("#dealRecordBtn").removeClass("record_arrow_on");
			$("#dealRecord").hide();
		});
		
		//群组发送开关
		$("#groupSendInput").on("click",function(){
			if( $(this).prop("checked")){
				if( warnMessageInfoObj.hasContent == true ){
					$("#phoneNums").empty().html(warnMessageInfoObj.htmlContent);
				}else{
					alert("未配置景区管理人员，无法使用群组发送功能！");
					return false;
				}
			}else{
				$("#phoneNums").empty().html(warnMessageInfoObj.defaultContent);
			}
		});
	});
});

/**
 * 初始化页面
 * @author wucm
 * @date   2015-11-11T17:59:23+0800
 * @return {[type]}                 [description]
 */
function initPage() {
	//高度设置
	$(".box,.leftBox,.rightBox").height($("body").height());
	$(".left_list,.map").height($("body").height() - 80);
	$(".left_list ul").height($("body").height() - 42);
	$(window).resize(function() {
		$(".box,.leftBox,.rightBox").height($("body").height());
		$(".left_list,.map").height($("body").height() - 80);
		$(".left_list ul").height($("body").height() - 42);
	});
	//城市选择
	$(".cityDiv").click(function() {
		if (!$(this).hasClass("cityDivShow")) {
			$(".cityList").show();
			$(this).addClass("cityDivShow");

		} else {
			$(".cityList").hide();
			$(this).removeClass("cityDivShow")
		}
	});

	//左侧收缩
	$(".leftBox .switch").click(function() {
		if (!$(this).hasClass("switchShow")) {
			$(".leftBox").animate({
				opacity: "show",
				marginLeft: "-260px"
			}, "1000", function() {
				$(".leftBox").css("margin-left", -260);
				$(".leftBox .switch").addClass("switchShow");
			});
			$(".rightBox").animate({
				marginLeft: "0"
			}, "normal", function() {
				$(".rightBox").css("margin-left", 0);
			});
		} else {
			$(".leftBox").animate({
				opacity: "show",
				marginLeft: "0px"
			}, "1000", function() {
				$(".leftBox").css("margin-left", 0);
				$(".leftBox .switch").removeClass("switchShow");
			});
			$(".rightBox").animate({
				marginLeft: "230px"
			}, "normal", function() {
				$(".rightBox").css("margin-left", 260);
			});
		}
	});
	//左侧下钻
}

/**
 * 初始化页面数据
 * @returns
 */
function initPageData() {
	
	var par = "&regionId="+regionId;
	Util.ajax.postJsonSync(srvMap.get('querySubRegionInfo'),par,function(json,status){
		if(status){
			
			regionInfo = json.object.data;

			initRegionInfo();

			// 初始化地图 
			initMap();

			// 初始化天气预报
			initWeather();

			$("#warnDealSubmit").click(function(){
				submitDealWarn();
			});
			$("#warnDealCancel").click(function(){
				$("#iMessage").hide();
			});
			
			// 初始化预警信息
			initWarn();

			_intvl_all = setInterval(function() {
				initWarn();
			}, 1000 * 60);
			
			//初始化景区舒适度信息
			initComfort();

		}else{
			 alert('错误','数据异常！');   
		}
	});

}

function initRegionInfo() {
	latLngList = regionInfo.latLngList;
	centerLng = regionInfo.coreLongitude;
	centerLat = regionInfo.coreLatitude;
	zoomLevel = regionInfo.warnZoomLevel;
	var regionName = regionInfo.areaName;
	var upperName = regionInfo.upperName;

	var pathStr = '当前位置：全省->$1-><span class="scenicAttr">$2</span>';
	pathStr = pathStr.replace(/\$1/g, upperName);
	pathStr = pathStr.replace(/\$2/g, regionName);
	$("#cityName").html(upperName);
	$(".regionPath").html(pathStr);
	$("#regionName").html(regionName);
}

/**
 * 初始化地图
 */
function initMap() {
	if (typeof(BMap) == "undefined") {
		alert("网络延迟导致地图未正确加载，请手动刷新刷新页面重新加载");
		return;
	}
	if (!map) {
		var level = parseInt(zoomLevel);
		//		level += 1; // 因为取值默认是预警监控页面的地图缩放界别，所以都需要+1

		map = new BMap.Map("subRegionMap", {
			enableMapClick: false
		});

		// 卫星地图，三维地图
		//		map.addControl(new BMap.MapTypeControl({
		//			type: BMAP_MAPTYPE_CONTROL_MAP,
		//			anchor: BMAP_ANCHOR_TOP_RIGHT,
		//			mapTypes: [BMAP_HYBRID_MAP]
		//		}));

		var point = new BMap.Point(centerLng, centerLat);
		map.centerAndZoom(point, level);
		map.setMinZoom(level-2); 
		map.setMaxZoom(level+2);
		map.enableScrollWheelZoom(true);
		//地图加载完后触发
//		map.addEventListener("tilesloaded", function(e) {
//			refreshCamera();
//		});
		
		map.addEventListener('moveend', refreshCamera);
		map.addEventListener('zoomend', refreshCamera);
		//增加移动和缩放事件
//		if (document.createElement('canvas').getContext) { // 判断当前浏览器是否支持绘制海量点
//			map.addEventListener('moveend', refreshCamera);
//			map.addEventListener('zoomend', refreshCamera);
//			refreshCamera();
//		} else {
//			alert('请在chrome、safari、IE8+以上浏览器查看本示例');
//		}
	}

	// 绘制边界
	createPolygon();
}

function initWarn() {
	clearMap();
	
	var par = "&regionId="+regionId;
	Util.ajax.postJsonSync(srvMap.get('querySubRegionWarn'),par,function(json,status){
		if(status){
			var regionWarn = json.object.result[0];
			clearMap();
			initWarnInfo(regionWarn);
			initWarnMarker(regionWarn);
			
			var warnInfo =  json.object.warnInfo;
			if(null != warnInfo){
				initWarnDeal(warnInfo);
			}
			
			var dealList =  json.object.dealList;
			initWarnDealRecord(dealList, regionWarn);
		}else{
			 alert('错误','数据异常！');   
		}
	});
}

function initWarnDeal(warnInfo){
	var warnLevel =warnInfo.warnLevel;
	var time = warnInfo.time;
	var regionName = warnInfo.regionName;
	var stayPersonCnts = warnInfo.stayPersonCnts;
	var msgContent = "";
	var par = "&warnId="+warnId;
	Util.ajax.postJsonSync(srvMap.get('queryWarnDealInfoById'),par,function(json,status){
		if(status){
			msgContent=json.object.result
		}else{
			 alert('错误','数据异常！');   
		}
	});
//	if( warnLevel == '红色' ){
//		msgContent = warnLevel+"告警：【"+regionName+"】景区，"+time+"游客数达到"+stayPersonCnts+"人，请限制景区客流量。";
//	}else if( warnLevel == '橙色' ){
//		msgContent = warnLevel+"预警：【"+regionName+"】景区，"+time+"游客数达到"+stayPersonCnts+"人，请提前做好景区客流量控制。";
//	}else{
//		msgContent = warnLevel+"预警：【"+regionName+"】景区，"+time+"游客数达到"+stayPersonCnts+"人，请密切关注景区客流量。";
//	}
	$("#msgContent").html(msgContent);
	
	warnMessageInfoObj = {};
	var managerInfoList = warnInfo.managerInfo;
	
	//加载管理人员手机号码
	var phoneListHtml = "";
	var strFormat = '<li><input id="phoneId_$1" onblur="checkNameUnique(this)" type="text" maxlength="11" value="$2" disabled="disabled" title="$3"/>' +
			'<span id="phoneDelId_$1" onclick="delPhoneOnclick(this)">-</span></li>';
	for( var i=0; i<managerInfoList.length; i++ ){
		phoneListHtml += strFormat.replace(/\$1/g, i)
								  .replace(/\$2/g, managerInfoList[i].phone)
								  .replace(/\$3/g, managerInfoList[i].name);
	}
	
	warnMessageInfoObj.defaultContent = '<li><input id="phoneId_0" onblur="checkNameUnique(this)" type="text" maxlength="11" placeholder="请输入号码"/>' +
	'<span id="phoneDelId_0" onclick="delPhoneOnclick(this)">-</span></li>';
	if( phoneListHtml.length == 0 ){
		phoneListHtml += warnMessageInfoObj.defaultContent;
		
		//群组发送取消选择
		$("#groupSendInput").prop("checked",false);
		$("#groupSendInput").attr("disabled","disabled");
		warnMessageInfoObj.hasContent = false;
	}else{
		$("#groupSendInput").prop("checked",true);
		$("#groupSendInput").removeAttr("disabled");
		warnMessageInfoObj.hasContent = true;
	}
	phoneListHtml += '<span id=\"addPhone\" onclick=\"addPhoneOnclick(this)\">+ </span> </ul>';
	$("#phoneNums").empty().html(phoneListHtml);
	
	warnMessageInfoObj.defaultContent += '<span id=\"addPhone\" onclick=\"addPhoneOnclick(this)\">+ </span> </ul>';
	warnMessageInfoObj.htmlContent = phoneListHtml;
	
}

/**
 * 初始化预警处理记录
 * @param dealList
 */
function initWarnDealRecord(dealList, regionWarn){
	var _o = $(".record_process_ul");
	_o.empty();
	var liHtml = "";
	if(null != dealList && dealList.length > 0){
		var recordLength = dealList.length;
		for(i=0; i<recordLength; i++){
			liHtml = '<li><span class="time">$1</span> 人群超标 <span class="warn_red">$2</span> 预警, <span class="warn_red">$3</span> <span>$4</span> <span class="warn_blue" title="$5">$6</span></li>';
			var rObj = dealList[i];
			liHtml = liHtml.replace("$1", rObj.dealTime);
			liHtml = liHtml.replace("$2", regionWarn.warnLevelName);
			liHtml = liHtml.replace("$3", rObj.dealStaffId);
			if("1" == rObj.dealTypeId){
				liHtml = liHtml.replace("$4", "一键转发处理");
			}else{
				liHtml = liHtml.replace("$4", "系统自动转发处理");
			}
			var receiveNumStr = rObj.receiveMsisdn;
			liHtml = liHtml.replace("$5", receiveNumStr);
			if(receiveNumStr.length > 20){
				receiveNumStr = receiveNumStr.substr(0, 35);
			}
			liHtml = liHtml.replace("$6", receiveNumStr);
			_o.append($(liHtml));
		}
	}
}

/**
 * 删除号码按钮点击事件
 */
function delPhoneOnclick(obj){
	var length = $("#phoneNums li").length;
	if (length<=1) {
		return;
	}
	var parentNode = obj.parentNode.parentNode;
	var phoneId = $(obj).attr("id").replace("phoneDelId","phoneId");
	var delObj = document.getElementById(phoneId);
	parentNode.removeChild(obj.parentNode);
};

/**
 * 加载预警信息
 * @param regionWarn
 */
function initWarnInfo(regionWarn) {
	var currFlow = regionWarn.stayPersonCnts;
	var dayFlow = regionWarn.sumVstCnts;
	var warnLevelId = regionWarn.warnLevelId;
	var warnLevelName = regionWarn.warnLevelName;
	warnId = regionWarn.warnId;
	$("#regionFlow").html(currFlow+"人");
	$("#currFlow").html(currFlow);
	$("#dayFlow").html(dayFlow);
}

/**
 * 加载预警图标
 * @param regionWarn
 */
function initWarnMarker(regionWarn) {
	drawMarker(regionWarn);
}

/**
 * 
 * @param regionWarn
 */
function drawMarker(regionWarn) {
	var regionName = regionInfo.areaName;
	var stayPersonCnts = regionWarn.stayPersonCnts;
	var warnLevelId = regionWarn.warnLevelId;
	var warnLevelName = regionWarn.warnLevelName;

	var pt = new BMap.Point(centerLng, centerLat);

	// marker图标
	var myIcon_src = CONTENT_PATH + "/zhly/assets/css/images/person/bg_level_0.png";
	var myIcon_src_on = CONTENT_PATH + "/zhly/assets/css/images/person/bg_level_0_on.png";
	var myIcon_src_warn = CONTENT_PATH + "/zhly/assets/css/images/person/";
	if ("" != warnLevelId && null != warnLevelId && undefined != warnLevelId) {
		myIcon_src = myIcon_src.replace(0, warnLevelId);
	}
	myIcon_src_on = myIcon_src_on.replace(0, warnLevelId);

	var warnHtml = "$1预警：<span> 1 </span> 个  <span style='background: #289cff; border-radius:3px;display:block;float:right;color:#ffffff;width:46px; text-align:center;' class='dealWarn'>处理</span>";
	warnHtml = warnHtml.replace("$1", warnLevelName);

	var labelColor = labelColorGreen;
	switch (warnLevelId) {
		case "1":
			{
				labelColor = labelColorYellow;
				$(".pc1").css("background", "url(assets/css/images/alarm_yellow.gif) no-repeat center center");
				$(".warnSpliy").show();
				$(".warnType").html(warnHtml).show();
				myIcon_src_warn += "img_icon_yellow_small.gif";
				break;
			}
		case "2":
			{
				labelColor = labelColorOrange;
				$(".pc1").css("background", "url(assets/css/images/alarm_orange.gif) no-repeat center center");
				$(".warnSpliy").show();
				$(".warnType").html(warnHtml).show();
				myIcon_src_warn += "img_icon_orange_small.gif";
				break;
			}
		case "3":
			{
				labelColor = labelColorRed;
				$(".pc1").css("background", "url(assets/css/images/alarm_red.gif) no-repeat center center");
				$(".warnSpliy").show();
				$(".warnType").html(warnHtml).show();
				myIcon_src_warn += "img_icon_red_small.gif";
				break;
			}
		default:
			{
				$("#dealRecordBtn").hide();
				$(".pc1").css("background", "url(assets/css/images/alarm_green.png) no-repeat center center");
				break;
			}
	}
	
	// 绑定预警处理
	$(".dealWarn").unbind("click").click(function(){
		$("#iMessage").show();
	});

	// marker图标尺寸
	var myIcon_size = new BMap.Size(71, 32);
	var myIcon_size_on = new BMap.Size(71, 32);
	var myIcon_size_warn = new BMap.Size(40, 44);

	var myIconNew = new BMap.Icon(myIcon_src, myIcon_size);
	var marker = new BMap.Marker(pt, {
		icon: myIconNew
	});
	map.addOverlay(marker);
	warnMarkerArr.push(myIconNew);

	var labelStr = '<p class="warnPoint">$2 $3人</p><div class="warnning_corner2"><img src="assets/css/images/person/icon_map_arr3.png" /></div>';
	labelStr = labelStr.replace(/\$2/g, regionName);
	labelStr = labelStr.replace(/\$3/g, stayPersonCnts);

	var opts = {
		position: pt,
		offset: new BMap.Size(-15, -40)
	};

	opts = getOptsBySpecialCode(pt, regionId);

	var label = new BMap.Label(labelStr, opts);
	label.setStyle({
		color: "#ffffff",
		borderRadius: "3px",
		fontSize: "14px",
		fontWeight: "bold",
		//		padding: "6px",
		fontFamily: "微软雅黑",
		lineHeight: "30px",
		minWidth: "100px",
		background: labelColor,
		borderColor: labelColor,
		textAlign: "center"
	});
	marker.setLabel(label);
	allWarnMarkerArr.push(marker);

}

/**
 * 
 * @Description :绘制边界
 * @author  menxl 
 * @date 创建时间：2015年11月12日 上午10:14:22 
 * @version 1.0
 */
function createPolygon() {
	var points = latLngList.split(";");
	var arrayPt = [];
	for (var k = 0; k < points.length; k++) {
		var pt = points[k].split(',');
		var point = new BMap.Point(pt[0], pt[1]);
		arrayPt.push(point);
	}
	var polygon = new BMap.Polygon(arrayPt, {
		fillColor: "#000000",
		fillOpacity: 0.1,
		strokeOpacity: 1,
		strokeWeight: 2,
		strokeColor: "#00daff"
	}); // 创建多边形
	//地图上添加所有区域边界
	map.addOverlay(polygon);
}

/**
 * 根据特殊的编码要求，设置不同的label标签显示位置
 * 
 * @author menxl
 * @date 创建时间：2015年11月12日 上午10:14:22 
 * @version 1.0
 */
function getOptsBySpecialCode(pt, code) {
	var opts = {
		position: pt, // 指定文本标注所在的地理位置
		offset: new BMap.Size(-15, -40)
			// 设置文本偏移量
	};
	var showLeftStr1 = "571F0105,571F0110,57920103,571B01,"; // 居左
	var showLeftStr2 = "571F0117,571F0118,"; // 居中
	var showTopStr = "57920104,"; // 居上
	var showLeftTopStr = "571B0202,57410101,571F0116,571F0107,"; // 居左上
	var showRightTopStr = "571F0108,571F0109,"; // 居右上

	if (showLeftStr1.indexOf(code + ",") >= 0) {
		opts = {
			position: pt, // 指定文本标注所在的地理位置
			offset: new BMap.Size(-110, 10)
				// 设置文本偏移量
		};
	} else if (showLeftStr2.indexOf(code + ",") >= 0) {
		opts = {
			position: pt, // 指定文本标注所在的地理位置
			offset: new BMap.Size(-50, 18)
				// 设置文本偏移量
		};
	} else if (showTopStr.indexOf(code + ",") >= 0) {
		opts = {
			position: pt, // 指定文本标注所在的地理位置
			offset: new BMap.Size(-50, -48)
				// 设置文本偏移量
		};
	} else if (showLeftTopStr.indexOf(code + ",") >= 0) {
		opts = {
			position: pt, // 指定文本标注所在的地理位置
			offset: new BMap.Size(-125, -38)
				// 设置文本偏移量
		};
	} else if (showRightTopStr.indexOf(code + ",") >= 0) {
		opts = {
			position: pt, // 指定文本标注所在的地理位置
			offset: new BMap.Size(10, -38)
				// 设置文本偏移量
		};
	}

	return opts;
}

function initWeather() {
	var cityName = regionInfo.upperName;
	BWeather.weather(cityName, function callback(data) {
		var mainWeatherCity = data.results[0].currentCity;
		var mainWeather = data.results[0].weather_data[0].weather; //天气：多云..等
		var mainTemperature = data.results[0].weather_data[0].date.substring(14, 17); //气温：5℃
		//var icon = data.results[0].weather_data[0].dayPictureUrl;
		var pm25 = data.results[0].pm25;
		$("#mainWeatherCity").html(mainWeatherCity);
		$("#mainWeather").html(mainWeather);
		$("#mainTemperature").html(mainTemperature);
		$("#weatherIcon").css("width:auto", null);
		//$("#weatherIcon").css("background", "url(" + icon + ") no-repeat center center");
		//处理天气面板
		var wBoxULHtml="";
		var weatherData = data.results[0].weather_data;
		var todayH1="";
		for (var i = 0; i < weatherData.length; i++) {
			var tStr ="";
			if (i == 0) {
				var h1=weatherData[0].date;
				todayH1 = "<span>$h1</span>";
				todayH1=todayH1.replace(/\$h1/g,h1);
				var temperature = weatherData[i].temperature;
				var weather = weatherData[i].weather;
				var wind = weatherData[i].wind
				var weatherPic=getWeatherPic(weather);
				$("#weatherIcon").css("background", "url(" + weatherPic + ") no-repeat center center");
				$("#weatherIcon").css("background-size", "70%");
				$("#weatherIcon").css("background-color", "#C8D6FD");
				
				tStr="<li ><div class=\"today_weather\"><div class=\"big_icon_weather\">" +
				//assets/css/images/weather/TB_yin.png
						"<img src=\"$wPic\" width=\"70\" height=\"70\"  alt=\"\"/></div>" +
						"<h2>$temperature</h2><h3>$weather</h3>" +
						"<p>$wind</p><p>空气质量：<i style=\"background-color:$color\">$pm25</i></p></div></li>";
				tStr = tStr.replace(/\$temperature/g,temperature);
				tStr = tStr.replace(/\$weather/g,weather);
				tStr = tStr.replace(/\$wind/g,wind);
				tStr = tStr.replace(/\$wPic/g,weatherPic);
				if (pm25<=50) {
					tStr = tStr.replace(/\$pm25/g,pm25+"优");
					tStr = tStr.replace(/\$color/g,"#6EB720");
				}else if (pm25>50 && pm25<=100) {
					tStr = tStr.replace(/\$pm25/g,pm25+"良");
					tStr = tStr.replace(/\$color/g,"#D6C60F");
				}else if (pm25>100 && pm25<= 150) {
					tStr = tStr.replace(/\$pm25/g,pm25+"轻度污染");
					tStr = tStr.replace(/\$color/g,"#EC7E22");
				}else if (pm25>150 && pm25<=200) {
					tStr = tStr.replace(/\$pm25/g,pm25+"中度污染");
					tStr = tStr.replace(/\$color/g,"E92D00");
				}else if (pm25>200) {
					tStr = tStr.replace(/\$pm25/g,pm25+"重度污染");
					tStr = tStr.replace(/\$color/g,"#B414BB");
				}
			}else {
				var week = weatherData[i].date;
				var date = getDateByNum(i);
				var temperature = weatherData[i].temperature;
				var weather = weatherData[i].weather;
				var wind = weatherData[i].wind;
				var weatherPic=getWeatherPic(weather);
				tStr = " <li ><div class=\"next_weather\">" +
				"<p>$week</p><p class=\"pgreycolor\">$date</p><div class=\"min_icon_weather\"> " +
				//assets/css/images/weather/TB_yin_min.png
				"<img src=\"$wPic\" width=\"45\" height=\"45\"  alt=\"\"/></div>" +
				"<p>$temperature</p><p>$weather</p><p>$wind</p></div></li>"
				tStr = tStr.replace(/\$week/g,week);
				tStr = tStr.replace(/\$date/g,date);
				tStr = tStr.replace(/\$temperature/g,temperature);
				tStr = tStr.replace(/\$weather/g,weather);
				tStr = tStr.replace(/\$wind/g,wind);
				tStr = tStr.replace(/\$wPic/g,weatherPic);
			}
			wBoxULHtml+=tStr;
		}
		$("#weatherBoxH1").html(todayH1);
		$("#weatherBoxUL").html(wBoxULHtml);
	});
	
}


/**
 * 生成日期
 * @param num
 * @returns
 */
function getDateByNum(num){
	var dd = new Date(); 
	dd.setDate(dd.getDate()+num);//获取AddDayCount天后的日期 
	var m = dd.getMonth()+1;//获取当前月份的日期 
	var d = dd.getDate(); 
	if(m<10){m="0"+m;}
	if(d<10){d="0"+d;}
	return m+"月"+d+"日"; 
}

/**
 * 生成天气PIC路径
 * @param num
 * @returns
 */
function getWeatherPic(weather,flag){
	var url="";
	//assets/css/images/weather/TB_yin.png
	if (weather.indexOf("雨夹雪")>-1) {
		url="assets/css/images/weather/sleet.png";
	}else if (weather.indexOf("暴雪")>-1) {
		url="assets/css/images/weather/snow_biggest.png";
	}else if (weather.indexOf("大雪")>-1) {
		url="assets/css/images/weather/snow_big.png";
	}else if (weather.indexOf("中雪")>-1) {
		url="assets/css/images/weather/snow_mid.png";
	}else if (weather.indexOf("小雪")>-1) {
		url="assets/css/images/weather/snow_small.png";
	}else if (weather.indexOf("暴雨")>-1) {
		url="assets/css/images/weather/rain_biggest.png";
	}else if (weather.indexOf("大雨")>-1) {
		url="assets/css/images/weather/cloudy_sun.png";
	}else if (weather.indexOf("中雨")>-1) {
		url="assets/css/images/weather/rain_mid.png";
	}else if (weather.indexOf("小雨")>-1) {
		url="assets/css/images/weather/rain_small.png";
	}else if (weather.indexOf("雨")>-1) {
		url="assets/css/images/weather/rain_small.png";
	}else if (weather.indexOf("阴")>-1) {
		url="assets/css/images/weather/overcast.png";
	}else if (weather.indexOf("雾")>-1) {
		url="assets/css/images/weather/fog.png";
	}else if (weather.indexOf("多云")>-1) {
		url="assets/css/images/weather/cloudy_sun.png";
	}else if (weather.indexOf("晴")>-1) {
		url="assets/css/images/weather/sunny_sun.png";
	}else if (weather.indexOf("扬")>-1) {
		url="assets/css/images/weather/sand_blowing .png";
	}else if (weather.indexOf("雷阵雨")>-1) {
		url="assets/css/images/weather/thunder_shower .png";
	}else if (weather.indexOf("雷")>-1) {
		url="assets/css/images/weather/thunder .png";
	}else {
		url="assets/css/images/weather/default.png";
	}
	return url;
}

function clearMap() {
	if (null == map) {
		return;
	}

	// 删除marker
	for (var key in warnMarkerArr) {
		var marker = warnMarkerArr[key];
		map.removeOverlay(marker);
	}
	for (var key in allWarnMarkerArr) {
		var marker = allWarnMarkerArr[key];
		map.removeOverlay(marker);
	}
	warnMarkerArr = [];
	allWarnMarkerArr = [];
}

/**
 * 预警处理
 */
function submitDealWarn(){
	var checkPhoneFlag=true;
	var phones = "";
	var msgContent = "";
	msgContent = $("#msgContent").html().trim();
	if (msgContent==null||msgContent=="") {
		checkPhoneFlag = false;
	}
	$(".numberBox2 ul li input").each(function (){
		var flag = checkNameUnique($(this));
		if (!flag) {
			checkPhoneFlag=false;
		}
		var phone = $(this).val().trim();
		if (phone!=null) {
			phones+=phone+',';
		}
	});
	if (!checkPhoneFlag) {
		return;
	}
	var par = "&warnId="+warnId+"&phones="+phones+"&msgContent="+msgContent;
	Util.ajax.postJsonSync(srvMap.get('warnDealById'),par,function(json,status){
		if(status){
			alert("处理成功！");
			$("#iMessage").hide();
		}else{
			 alert('错误','数据异常！');   
		}
	});
}

/**
 * 添加号码按钮点击事件
 */
function addPhoneOnclick(obj){
	var parentNode = obj.parentNode;
	parentNode.removeChild(obj);
	var li = document.createElement('li'); 
	var rand = Math.random();
	li.innerHTML = "<input id=\"phoneId_"+rand+"\"  onblur=\"checkNameUnique(this)\"  maxlength=\"11\" placeholder=\"请输入号码\" type=\"text\"><span id=\"phoneDelId_"+rand+"\" onclick=\"delPhoneOnclick(this)\">-</span>";
	spanHtml="<span id=\"addPhone\" onclick=\"addPhoneOnclick(this)\">+</span>";
	parentNode.appendChild(li);
	$("#phoneNums").append(spanHtml);
};

/**
 * 校验电话输入框
 * @returns {String}
 */
function checkNameUnique(obj){
	var inputStr = $(obj).val().trim();
	var reg = /^0?1[3|4|5|8][0-9]\d{8}$/;
	if (inputStr!=null&&reg.test(inputStr)) {
		$(obj).css("border","1px solid #f2f2f2");
		return true;
	}else{
		$(obj).css("border","1px dotted red");
		return false;
	}
}

/**
 * 
 * @Description : 进入热力图
 * @return void
 * 
 * @author : wucm
 * @date : 2015年7月2日 上午9:22:12
 * 
 */
function gotoHotMap() {
	if ($("#sub_map_link").hasClass("map_link_grey")) {
		return;
	}
	var areaId = regionId;
	var areaId = areaId.EncodeBase64(); // 可能是市编码，也可能是监控区编码
	var str = '?areaId=' + areaId;
	window.open(CONTENT_PATH + '/zhly/hot_map.jsp' + str, '_self');
}


/**
 * 
 * @Description : 进入趋势分析
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月20日 上午9:22:12
 * 
 */
function gotoTrendAnalysis() {
	var urlParams = getParamStr();
	var url = CONTENT_PATH + '/zhly/analysis_trend.jsp' + urlParams;
	window.open(encodeURI(url), '_self');
}

/**
 * 
 * @Description : 进入结构分析
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月20日 上午9:22:12
 * 
 */
function gotoPortraitAnalysis() {
	var urlParams = getParamStr();
	var url = CONTENT_PATH + '/zhly/portrait_tourist.jsp' + urlParams;
	window.open(encodeURI(url), '_self');
}

/**
 * 
 * @Description : 进入来源分析
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月20日 上午9:22:12
 * 
 */
function gotoSourceAnalysis() {
	var urlParams = getParamStr();
	var url = CONTENT_PATH + '/zhly/analysis_come.jsp' + urlParams;
	window.open(encodeURI(url), '_self');
}

/**
 * 
 * @Description : 进入轨迹分析
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月20日 上午9:22:12
 * 
 */
function gotoTrackAnalysis() {
	var urlParams = getParamStr();
	var url = CONTENT_PATH + '/zhly/analysis_track.jsp' + urlParams;
	window.open(encodeURI(url), '_self');
}

/**
 * 
 * @Description : 获取景区id和景区名称，用于传送参数给分析功能模块
 * @return void
 * 
 * @author : xuxiong
 * @date : 2015年12月29日 上午9:22:12
 * 
 */
function getParamStr(){
	var _regionId = regionId;
	_regionId = _regionId.EncodeBase64();
	var regionName = $("#regionName").html();
	regionName = encodeURIComponent(regionName);
	
	return '?regionId=' + _regionId + '&regionName=' + regionName;
}

/**
 * 
 * @Description : 摄像头按钮点击
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function cameraClick() {
	if (cameraFlag == 'open') {
		closeCamera();
		cameraFlag = "close";
	}else {
		showCamera();
		cameraFlag = "open";
	}
}

/**
 * 
 * @Description : 刷新摄像头
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function refreshCamera(){
//	alert("刷新摄像头");
	if (cameraFlag == 'open') {
		showCamera();
	}
}

/**
 * 
 * @Description : 展示摄像头
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function showCamera(){
	closeCamera();
	var maxMinPos = getMaxMinPos();
	var par = "&maxLng="+maxMinPos[0].lng+"&maxLat="+maxMinPos[0].lat+"&minLng="+ maxMinPos[1].lng+"&minLat="+maxMinPos[1].lat;
	Util.ajax.postJsonSync(srvMap.get('queryCamera'),par,function(json,status){
		if(status){
			buildCamera(json.object);
		}else{
			 alert('错误','数据异常！');   
		}
	});

}

function buildCamera(data){
	for (var i = 0; i < data.length; i++) {
		var lng = data[i].longitude;
		var lat  = data[i].latitude;
		var pt = new BMap.Point(lng, lat);
		var myIcon = new BMap.Icon("./assets/css/images/map_icon_camr.png", new BMap.Size(34,104));
		var marker2 = new BMap.Marker(pt,{icon:myIcon});  // 创建标注
		map.addOverlay(marker2);              // 将标注添加到地图中
		
		cameraMarkerList.push(marker2);
	}
}

/**
 * 
 * @Description : 隐藏摄像头
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function closeCamera(){
	for (var i = 0; i < cameraMarkerList.length; i++) {
		map.removeOverlay(cameraMarkerList[i]);
	}
	cameraMarkerList=[];
}

/**
 * 根据传入的百度坐标序列，返回最大最小值坐标点
 * @param {BMap.Points []}
 */
function getMaxMinPos() {
	var abs = map.getBounds(); // 获取可视区域

	var abssw = abs.getSouthWest(); // 可视区域左下角
	var absne = abs.getNorthEast(); // 可视区域右上角
	var BPoints = [];
	BPoints.push(abssw);
	BPoints.push(absne);
	var lngs = [];
	var lats = [];
	for (var i = 0; i < BPoints.length; i++) {
		var bp = BPoints[i];
		lngs.push(bp.lng);
		lats.push(bp.lat);
	}
	var maxMinPos = [];
	maxMinPos.push(new BMap.Point(getArrMaxMin(lngs, 'max'), getArrMaxMin(lats,
		'max')));
	maxMinPos.push(new BMap.Point(getArrMaxMin(lngs, 'min'), getArrMaxMin(lats,
		'min')));
	// 返回百度坐标点
	return maxMinPos;
}

/**
 * 查询出最大最小值
 */
function getArrMaxMin(arr, minOrMax) {
	var rtnVal = arr[0];
	// 遍历数组，查询出最大最小值
	for (var i = 1; i < arr.length; i++) {
		if (minOrMax == 'max') {
			if (rtnVal < arr[i])
				rtnVal = arr[i];
		} else if (minOrMax == 'min') {
			if (rtnVal > arr[i])
				rtnVal = arr[i];
		}
	}
	return rtnVal;
}


/**
 * 
 * @Description :客流预测
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function trendForecastClick(){
	
	if (trendFlag == "open") {
		$(".passenger_flow_forecasting").hide();
		trendFlag = "close";
	}else {
		initTrend();
		$(".passenger_flow_forecasting").show();
		trendFlag = "open";
	}
	
}

/**
 * 
 * @Description :客流预测取值
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function initTrend(){
	var par = "&regionId="+regionId;
	Util.ajax.postJsonSync(srvMap.get('trendForecast'),par,function(json,status){
		if(status){
			buildTrend(json.object);
		}else{
			 alert('错误','数据异常！');   
		}
	});
}

/**
 * 
 * @Description :展示客流预测
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function buildTrend(data){
	var lineData = [];
	var xData = [];
	if(data==''){
		lineData = [''];
		xData = [''];
	}
	for (var i = 0; i < data.length; i++) {
		lineData.push(data[i].vstPersonCnts);
		xData.push(data[i].forecastDate);
	}
	
	require.config({
		paths: {
			echarts: CONTENT_PATH + '/common/js'
		}
	});
	require(['echarts', 'echarts/chart/line'], function(ec) {
		
		option = {
			title: {
				text: ''
			},
			legend: {
				x:'right',
		        data:['一周预测']
		    },
			tooltip: {
				trigger: 'item',
				formatter: "{b}:<br/> {a}：{c}"
			},
			calculable: false,
			/*grid: {
				borderWidth: 0,
				x: 90,
				y: 60,
				x2: 90,
				y2: 40,
				borderColor: '#424242'
			},*/
			xAxis: [{
				name: "日期",
				type: 'category',
				boundaryGap: false,
//				axisLabel:_axisLabel,
				data: xData
			}],
			yAxis: [{
				name: "人数",
				type: 'value',
				show: true
			}],
			series: [{
				name: '一周预测',
				type: 'line',
				markPoint: {
					//symbol:'emptyRectangle',
					data: [{
						type: 'max',
						name: '最大值'
					}, {
						type: 'min',
						name: '最小值'
					}]
				},
				data: lineData
			}]
		};

		myChart_trendCharts = ec.init(document.getElementById('trendForecastDiv'), 'macarons');
		myChart_trendCharts.clear();
		myChart_trendCharts.setOption(option);
	});
}

/**
 * 
 * @Description :设置用户权限
 * @return void
 * 
 * @author : pengjy
 * @date : 2016年07月26日 上午9:22:12
 * 
 */
function initFuncAuth(){
	var allAuth = $("#funcAuth", window.parent.document).html();
	if (allAuth.indexOf("analysis_trend.jsp")>-1) {
		$("#gotoTrendAnalysis").show();
	}
	if (allAuth.indexOf("analysis_come.jsp")>-1) {
		$("#gotoSourceAnalysis").show();
	}
	if (allAuth.indexOf("hot_map.jsp")>-1) {
		$("#gotoHotMap").show();
	}
	if (allAuth.indexOf("portrait_tourist.jsp")>-1) {
		$("#gotoPortraitAnalysis").show();
	}
	if (allAuth.indexOf("analysis_track.jsp")>-1) {
		$("#gotoTrackAnalysis").show();
	}
}

//初始化景区舒适度信息
function initComfort(){
	var par = "&regionId="+regionId;
	Util.ajax.postJsonSync(srvMap.get('queryComfortLevel'),par,function(json,status){
		if(status){
			var comfortable_level=json.object[0].comfortable_level;
			$("#comfort_value").text(comfortable_level);
			$("#comfort_desc").text(json.object[0].comfortable_level_desc);
			//初始化舒适度星级展示
			initStarShow(comfortable_level);			
		}else{
			 alert('查询舒适度信息出错！');   
		}
	});
}

function initStarShow(cnt){
	//舒适度指数除2取整得到中间值
	var mid_cnt=cnt/2;
	//小于等于中间值的点亮
	for(var i=1;i<=mid_cnt;i++){
		$("#star_"+i).removeClass("li_gray");
		$("#star_"+i).addClass("li_yellow");
	}
	//舒适度指数对2取模,对不能整除的点亮半星
	if(cnt%2 != 0){
		var half_index=parseInt(mid_cnt)+1;
		$("#star_"+half_index).removeClass("li_gray");
		$("#star_"+half_index).addClass("li_half");
	}
	
}